package com.atguigu.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {


    private static Integer tokenExpiration=1; //令牌过期时间为1小时

    private static String tokenSignKey="gulimail";  //令牌签名密钥

    private static String messageOne="userId";

    private static String messageTwo="userName";

    /**
     * JWT token 生成
     * @param userId
     * @param userName
     * @return
     */
    public static String createToken(Long userId,String userName){

        Calendar calendar=Calendar.getInstance();

        calendar.add(Calendar.HOUR,tokenExpiration);

        String token= JWT.create()
                .withHeader(new HashMap<>())
                .withClaim(messageOne,userId)
                .withClaim(messageTwo,userName)
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(tokenSignKey));
        return token;
    }

    public static Map<String,String> resolveToken(String token){

        // 创建解析对象，使用的算法和secret要与创建token时保持一致
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(tokenSignKey)).build();
        // 解析指定的token
        try{
            DecodedJWT decodedJWT = jwtVerifier.verify(token);

            //检查是否过期
            if (decodedJWT.getExpiresAt().before(new Date())) {
                // Token 已过期，
                throw new RuntimeException("Token has expired");
            }

            // 获取解析后的token中的payload信息
            Claim userId = decodedJWT.getClaim(messageOne);
            Claim userName = decodedJWT.getClaim(messageTwo);

            //封装解析结果
            Map<String,String> result=new HashMap<>();
            result.put(messageOne,userId.asString());
            result.put(messageTwo,userName.asString());

            return result;
        } catch (Exception e){

            return null;

        }
    }

//    public static String getToken(Map<String,String> payload){
//        // 指定token过期时间为7天
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.DATE, 7);
//
//        JWTCreator.Builder builder = JWT.create();
//        // 构建payload
//        payload.forEach((k,v) -> builder.withClaim(k,v));
//        // 指定过期时间和签名算法
//        String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(SECRET));
//        return token;
//    }

}
